package src

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/sirupsen/logrus"
)

/*
统计角色的新旧设备id(旧设备有常用标识)
*/

type (
	//新旧设备
	devInfo struct {
		old  string
		newd string
	}
)

var (
	gDevids map[string]*devInfo = make(map[string]*devInfo) //openid-->
)

func DoStatONDevid() {
	//readf("20240824_19_15_22.log")
	readDir_devid()

	var (
		oldCnt int
		newCnt int
	)

	for k, v := range gDevids {
		if v.old != "" {
			oldCnt++
		}
		if v.newd != "" {
			newCnt++
			logrus.Printf(">>>>>>>>>>> openid:%s dev:%+v", k, v)
		}
	}
	logrus.Info("*************** totao user devids:", len(gDevids), ", olds:", oldCnt, ", news:", newCnt)
}

func readDir_devid() {
	var (
		paths = []string{"log", "log/old"}
	)
	for _, path := range paths {
		ds, err := os.ReadDir(path)
		if err != nil {
			log.Fatalf("read dir:%s err:%+v", path, err)
		}
		fmt.Println("--------- dir:", path)

		for _, v := range ds {
			if v.IsDir() {
				continue
			}
			if !strings.Contains(v.Name(), ".log") || strings.Contains(v.Name(), "_out") || strings.Contains(v.Name(), "_err") {
				continue
			}
			//fmt.Println(">>> file:", v.Name())
			readf_devid(path + "/" + v.Name())
			/* if k == 5 {
				return
			} */
		}
	}
}

func readf_devid(fs string) {
	f, err := os.Open(fs)
	if err != nil {
		log.Fatalf("read file:%s, err:%+v", fs, err)
		return
	}
	defer f.Close()

	var n int
	scan := bufio.NewScanner(f)
	for scan.Scan() {
		parseDevid(scan.Text())
		n++
	}
	if err := scan.Err(); err != nil {
		log.Fatal("scan err:", err)
	}
}

func parseDevid(str string) {
	var (
		openId         string
		oldDev, newDev string
	)

	//搜索关键字 "handle QLogin json" "handle Login, ip"
	if strings.Contains(str, "handle Login, ip") { //旧设备
		s := "Device:"
		st := " Devtype"
		i := strings.Index(str, s)
		it := strings.Index(str, st)
		if i != -1 && it != -1 && it-i >= len(s)+3 { //设备号不为空且>=3位
			oldDev = str[i+len(s) : it]
			if !isOldDev(oldDev) {
				return
			}
		}
		if oldDev == "" || len(oldDev) != 32 {
			return
		}

		s = "SdkUid:"
		i = strings.Index(str, s)
		if i == -1 {
			return
		}
		openId = str[i+len(s) : i+len(s)+28]
		if _, ok := gDevids[openId]; !ok { //绑定openid
			gDevids[openId] = &devInfo{old: oldDev}
		}
	} else if strings.Contains(str, "handle QLogin json") { //新设备
		s := "Device:"
		st := " SdkUid"
		i := strings.Index(str, s)
		it := strings.Index(str, st)
		if i != -1 && it != -1 && it-i >= len(s)+3 { //设备号不为空且>=3位
			newDev = str[i+len(s) : it]
			if isOldDev(newDev) {
				return
			}

			s = "SdkUid:"
			i = strings.Index(str, s)
			if i == -1 {
				return
			}
			openId = str[i+len(s) : i+len(s)+28]
			if v, ok := gDevids[openId]; ok { //已保存旧设备情况下 才保存新的
				if v.newd == "" {
					v.newd = newDev
				}
			}
		}
	}
}

func isOldDev(dev string) bool {
	var (
		s1 = dev[:1]
		s2 = dev[1:2]
		s3 = dev[2:3]
	)
	return s1 == "0" && (s2 >= "1" && s2 <= "9") && s3 == "1"
}
